<template>
    <div>
        <div class="search-suggestion">
            <van-cell v-for="(text, index) in suggestions" :key="index" icon="search" @click="$emit('search',text)">
                <div slot="title" v-html="highlight(text)"></div>
            </van-cell>
           
        </div>
    </div>
</template>
  
<script>
import { getSearchSuggestions } from '@/api/serach'

import { debounce } from 'lodash'
export default {  
    name: 'searchSuggestion',
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            suggestions: []
        }
    },
    watch: {
        searchText: {
            handler: debounce(function (value) {
                this.loadSearchSuggestions(value)
            }, 1000),
            immediate: true
        }
    },
    methods: {
        async loadSearchSuggestions(q) {
            try {
                const { data } = await getSearchSuggestions(q)
                this.suggestions = data.data.options
                // console.log(data);
            } catch (err) {
                this.$toast('获取数据失败，请稍后重试')
            }
        },
        highlight(text) {
            if (!text) return
            // console.log(text)
            const highlightStr = `<span class="active">${this.searchText}</span>`
            const reg = new RegExp(this.searchText, 'gi')
            return text.replace(reg, highlightStr)
        }
    }
}
</script>
  
<style lang="less" scoped >
.search-suggestion {
   /deep/ span.active {
        color: red;
    }
}
</style>